package com.baitengsoft.patentapimonitor.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.*;
import cn.hutool.core.io.resource.ClassPathResource;
import com.baitengsoft.patentapimonitor.api.model.dto.WebAnalysisExportDto;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.io.FileReader;
import java.util.*;

/**
 * 前端导出Excel工具类
 *
 * @author Chen 2018/1/30
 */
public class WebExcelUtils {

    /**
     * 前台-专利创造指标分析类导出
     */
    public static ResponseEntity<byte[]> createExcelFile(String fileName, byte[] bytes) {
        HttpHeaders headers = new HttpHeaders();
        try {
            String downloadFielName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            //通知浏览器以attachment（下载方式）
            headers.setContentDispositionFormData("attachment", downloadFielName);
            //application/octet-stream ： 二进制流数据（最常见的文件下载）。
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(bytes, headers, HttpStatus.CREATED);
    }

    /**
     * 获得指定文件的byte数组
     */

    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }


    public static Map<String, String> getMapExcel(String title) {
        Map<String, String> mapExcel = new HashMap<String, String>();
        mapExcel.put("title", title);
        return mapExcel;
    }

    public static Res exportExcelFile(List<WebAnalysisExportDto> webDtos, HttpServletResponse response, String fileName, String title){
        if (webDtos == null){
            return Res.error("无数据");
        }else {
            try {
                Map<String, String> mapExcel = WebExcelUtils.getMapExcel(title);
                fileName=new String(fileName.getBytes("gb2312"), "iso8859-1");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName);
                ExcelUtil.getInstance().exportObj2ExcelByTemplate(mapExcel, "web-analysis-template.xls",response.getOutputStream() ,
                        webDtos, WebAnalysisExportDto.class, true);
            }catch (Exception e){
                e.printStackTrace();
                return Res.error("导出出错");
            }
        }
        return Res.ok();
    }

    public static Res exportGeneralExcelFile(List<?> webDtos, HttpServletResponse response, String fileName, String title){
        if (webDtos == null||webDtos.size()<1){
            return Res.error("无数据");
        }else {
            try {
                Map<String, String> mapExcel = WebExcelUtils.getMapExcel(title);
                fileName=new String(fileName.getBytes("gb2312"), "iso8859-1");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName);
                ExcelUtil.getInstance().exportObj2ExcelByTemplate(mapExcel, "web-analysis-template.xls",response.getOutputStream() ,
                        webDtos, webDtos.get(0).getClass(), true);
            }catch (Exception e){
                e.printStackTrace();
                return Res.error("导出出错");
            }
        }
        return Res.ok();
    }
    public static Res exportSuminfoExcelFile(List<?> webDtos, HttpServletResponse response, String fileName,  Map<String, String> mapExcel){
        if (webDtos == null||webDtos.size()<1){
            return Res.error("无数据");
        }else {
            try {
                fileName=new String(fileName.getBytes("gb2312"), "iso8859-1");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName);
                ExcelUtil.getInstance().exportObj2ExcelByTemplate(mapExcel, "web-suminfo-template.xls",response.getOutputStream() ,
                        webDtos, webDtos.get(0).getClass(), true);
            }catch (Exception e){
                e.printStackTrace();
                return Res.error("导出出错");
            }
        }
        return Res.ok();
    }

    public static HSSFWorkbook getAnalysisReportBook() {
        HSSFWorkbook book = new HSSFWorkbook(); //创建book
        Sheet sheet1 = book.createSheet("工作进程表");
        Sheet sheet2 = book.createSheet("统计分析");
        Sheet sheet3 = book.createSheet("代理机构统计");
        Sheet sheet4 = book.createSheet("权利人统计");
        Sheet sheet5 = book.createSheet("监控汇总");
        Sheet sheet6 = book.createSheet("监控分析");
        return book;
    }


    public static String getNewFilePath(Integer platformId,String fileName) {
        ClassPathResource resource = new ClassPathResource("");
        File mkdir = FileUtil.mkdir(resource.getAbsolutePath()+"report/"+ platformId );
        return mkdir.getAbsolutePath()+ "/"+fileName;
    }
    public static String getUploadFilePath(Integer platformId,String fileName) {
        ClassPathResource resource = new ClassPathResource("");
        return resource.getAbsolutePath()+"upload/"+ platformId + "/"+fileName;
    }

    public static String getUploadFilePath1(Integer platformId) {
        ClassPathResource resource = new ClassPathResource("");
        return resource.getAbsolutePath()+"upload/"+ platformId;
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }



    public static void download(String filePath,String fileName,HttpServletResponse response) throws Exception{
        File file = new File(filePath);
        ServletOutputStream os = response.getOutputStream();
        fileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        cn.hutool.core.io.file.FileReader reader = new cn.hutool.core.io.file.FileReader(file,"UTF-8");
        reader.writeToStream(os);
        os.flush();
        os.close();
    }
}
